// 场景管理相关函数 - 第2部分

// 编辑场景
function editScene(sceneId) {
    $.ajax({
        url: `/scene/${sceneId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const scene = response.scene;
                
                // 重置表单
                $('#add-edit-form')[0].reset();
                
                // 设置表单模式
                $('#add-edit-form').data('mode', 'edit');
                $('#add-edit-form').data('id', scene.id);
                $('#addEditModalLabel').text('编辑场景');
                
                // 填充表单
                $('#scene-name').val(scene.name);
                $('#scene-description').val(scene.description);
                
                // 标签
                if (scene.tags && scene.tags.length > 0) {
                    $('#scene-tags').val(scene.tags.join(','));
                }
                
                // 加载API列表
                loadSceneApiList();
                
                // 渲染场景步骤
                renderSceneSteps(scene.steps);
                
                // 显示模态框
                $('#addEditModal').modal('show');
                
                // 初始化拖放功能
                initDragAndDrop();
            } else {
                showToast('error', response.message || '获取场景详情失败');
            }
        },
        error: function(error) {
            console.error('获取场景详情失败:', error);
            showToast('error', '获取场景详情失败');
        }
    });
}

// 渲染场景步骤
function renderSceneSteps(steps) {
    console.log("场景步骤数据：", steps);
    
    // 获取并清空步骤容器，但保留提示信息
    const stepsContainer = $('#steps-container');
    stepsContainer.empty();
    
    // 显示或隐藏提示信息
    const alertInfo = $('#scene-steps').find('.alert-info');
    if (!steps || steps.length === 0) {
        alertInfo.show();
        return;
    } else {
        alertInfo.hide();
    }
    
    steps.forEach(step => {
        let stepElement;
        console.log('渲染步骤:', step);
        
        switch (step.type) {
            case 'api':
                stepElement = createApiStep(step.name, step.api_id, step.api_name, step.api.method, step.api.path);
                break;
            case 'script':
                stepElement = createScriptStep(step.name, step.script);
                break;
            case 'condition':
                stepElement = createConditionStep(step.name, step.condition);
                break;
            case 'loop':
                stepElement = createLoopStep(step.name, step.loop_type, step.loop_count, step.loop_condition, step.loop_collection);
                break;
            default:
                console.error('未知的步骤类型:', step.type);
                return;
        }
        
        // 设置步骤ID
        $(stepElement).data('id', step.id);
        
        // 添加子步骤
        if (step.children && step.children.length > 0) {
            const childrenContainer = $(stepElement).find('.step-children');
            
            step.children.forEach(childStep => {
                let childElement;
                
                switch (childStep.type) {
                    case 'api':
                        childElement = createApiStep(childStep.name, childStep.api_id, childStep.api_name, childStep.method, childStep.url);
                        break;
                    case 'script':
                        childElement = createScriptStep(childStep.name, childStep.script);
                        break;
                    case 'condition':
                        childElement = createConditionStep(childStep.name, childStep.condition);
                        break;
                    case 'loop':
                        childElement = createLoopStep(childStep.name, childStep.loop_type, childStep.loop_count, childStep.loop_condition, childStep.loop_collection);
                        break;
                    default:
                        console.error('未知的子步骤类型:', childStep.type);
                        return;
                }
                
                // 设置子步骤ID
                $(childElement).data('id', childStep.id);
                
                childrenContainer.append(childElement);
            });
        }
        
        stepsContainer.append(stepElement);
    });
    
    // 更新步骤序号
    updateStepNumbers();
}

// 创建API步骤 - 增强版本，支持传入请求体和请求头
function createApiStep(name, apiId, apiName, method, url, body = null, headers = null) {
    stepCounter++;
    
    const methodBadgeClass = {
        'GET': 'bg-success',
        'POST': 'bg-primary',
        'PUT': 'bg-warning',
        'DELETE': 'bg-danger',
        'PATCH': 'bg-info'
    };
    
    const stepItem = $(`
        <div class="card mb-3 step-item" draggable="true" data-type="api" data-api-id="${apiId}">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <span class="step-number badge bg-secondary me-2">1</span>
                    <span class="badge ${methodBadgeClass[method] || 'bg-secondary'}">${method}</span>
                    <span class="ms-2">${name || apiName || 'API步骤'}</span>
                </div>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-secondary collapse-step">
                        <i class="bi bi-chevron-right"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger delete-step">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
            <div class="card-body step-body d-none">
                <div class="mb-3">
                    <label class="form-label">API名称</label>
                    <input type="text" class="form-control step-name" value="${name || apiName || ''}" placeholder="API名称">
                </div>
                <div class="mb-3">
                    <label class="form-label">请求URL</label>
                    <input type="text" class="form-control step-url" value="${url || ''}" placeholder="请求URL" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">请求方法</label>
                    <input type="text" class="form-control step-method" value="${method || ''}" placeholder="请求方法" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">请求体</label>
                    <textarea class="form-control step-body-json" rows="4" placeholder="请求体JSON内容"></textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">请求头</label>
                    <textarea class="form-control step-headers-json" rows="3" placeholder="请求头JSON内容"></textarea>
                </div>
            </div>
        </div>
    `);
    
    // 优先使用传入的请求体和请求头参数
    if (body) {
        stepItem.find('.step-body-json').val(JSON.stringify(body, null, 2));
        //console.log('使用传入的请求体参数:', body);
    }
    
    if (headers) {
        stepItem.find('.step-headers-json').val(JSON.stringify(headers, null, 2));
        //console.log('使用传入的请求头参数:', headers);
    }
    
    // 如果没有传入完整数据，尝试从window.apis获取补充信息
    if (apiId && (!body || !headers)) {
        console.log('尝试获取API详细信息，ID:', apiId);
        
        if (window.apis && window.apis[apiId]) {
            const apiDetails = window.apis[apiId];
            console.log('从window.apis获取到API详细信息:', apiDetails);
            
            // 确保URL字段正确设置 - 使用path字段
            if (apiDetails.path && !url) {
                url = apiDetails.path;
                stepItem.find('.step-url').val(url);
                console.log('从API详情设置URL:', url);
            }
            
            // 如果没有传入请求体，使用window.apis中的数据
            if (apiDetails.body && !body) {
                stepItem.find('.step-body-json').val(JSON.stringify(apiDetails.body, null, 2));
                console.log('从window.apis设置请求体:', apiDetails.body);
            }
            
            // 如果没有传入请求头，使用window.apis中的数据
            if (apiDetails.headers && !headers) {
                stepItem.find('.step-headers-json').val(JSON.stringify(apiDetails.headers, null, 2));
                console.log('从window.apis设置请求头:', apiDetails.headers);
            }
        } else {
            // 如果window.apis中没有找到，添加一些默认的示例数据
            console.log('window.apis中未找到API详细信息，使用默认示例数据');
            
            if (!url) {
                console.log('URL为空，设置默认值');
                url = '/api/default';
                stepItem.find('.step-url').val(url);
            }
            
            if (!body) {
                stepItem.find('.step-body-json').val(JSON.stringify({"example": "这是一个示例请求体"}, null, 2));
            }
            
            if (!headers) {
                stepItem.find('.step-headers-json').val(JSON.stringify({"Content-Type": "application/json"}, null, 2));
            }
        }
    }
    
    // 最后再次确保所有字段都已正确填充
    console.log('最终API步骤数据:', {
        url: stepItem.find('.step-url').val(),
        body: stepItem.find('.step-body-json').val(),
        headers: stepItem.find('.step-headers-json').val()
    });
    
    return stepItem;
}

// 创建脚本步骤
function createScriptStep(name, script) {
    stepCounter++;
    
    const stepItem = $(`
        <div class="card mb-3 step-item" draggable="true" data-type="script">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <span class="step-number badge bg-secondary me-2">1</span>
                    <span class="badge bg-info">脚本</span>
                    <span class="ms-2">${name || '脚本步骤'}</span>
                </div>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-secondary collapse-step">
                        <i class="bi bi-chevron-down"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger delete-step">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
            <div class="card-body step-body">
                <div class="mb-3">
                    <label class="form-label">脚本名称</label>
                    <input type="text" class="form-control step-name" value="${name || ''}" placeholder="脚本名称">
                </div>
                <div class="mb-3">
                    <label class="form-label">脚本代码</label>
                    <textarea class="form-control step-script" rows="5" placeholder="脚本代码">${script || ''}</textarea>
                </div>
            </div>
        </div>
    `);
    
    return stepItem;
}

// 创建条件步骤
function createConditionStep(name, condition) {
    stepCounter++;
    
    const stepItem = $(`
        <div class="card mb-3 step-item" draggable="true" data-type="condition">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <span class="step-number badge bg-secondary me-2">1</span>
                    <span class="badge bg-warning">条件</span>
                    <span class="ms-2">${name || '条件步骤'}</span>
                </div>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-secondary collapse-step">
                        <i class="bi bi-chevron-down"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger delete-step">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
            <div class="card-body step-body">
                <div class="mb-3">
                    <label class="form-label">条件名称</label>
                    <input type="text" class="form-control step-name" value="${name || ''}" placeholder="条件名称">
                </div>
                <div class="mb-3">
                    <label class="form-label">条件表达式</label>
                    <input type="text" class="form-control step-condition" value="${condition || ''}" placeholder="条件表达式">
                    <div class="form-text">例如：${name}.status == 200 或 ${name}.body.success == true</div>
                </div>
                <div class="mb-3">
                    <label class="form-label">子步骤</label>
                    <div class="step-children p-2 border rounded" style="min-height: 50px;">
                        <!-- 子步骤将在这里 -->
                    </div>
                </div>
            </div>
        </div>
    `);
    
    return stepItem;
}

// 创建循环步骤
function createLoopStep(name, loopType, loopCount, loopCondition, loopCollection) {
    stepCounter++;
    
    let loopInfo = '';
    
    if (loopType === 'count') {
        loopInfo = `循环 ${loopCount} 次`;
    } else if (loopType === 'while') {
        loopInfo = `当 ${loopCondition} 时循环`;
    } else if (loopType === 'foreach') {
        loopInfo = `遍历 ${loopCollection}`;
    }
    
    const stepItem = $(`
        <div class="card mb-3 step-item" draggable="true" data-type="loop" data-loop-type="${loopType}">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <span class="step-number badge bg-secondary me-2">1</span>
                    <span class="badge bg-primary">循环</span>
                    <span class="ms-2">${name || '循环步骤'}</span>
                </div>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-secondary collapse-step">
                        <i class="bi bi-chevron-down"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger delete-step">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
            <div class="card-body step-body">
                <div class="mb-3">
                    <label class="form-label">循环名称</label>
                    <input type="text" class="form-control step-name" value="${name || ''}" placeholder="循环名称">
                </div>
                <div class="mb-3">
                    <label class="form-label">循环类型</label>
                    <select class="form-select step-loop-type">
                        <option value="count" ${loopType === 'count' ? 'selected' : ''}>循环次数</option>
                        <option value="while" ${loopType === 'while' ? 'selected' : ''}>条件循环</option>
                        <option value="foreach" ${loopType === 'foreach' ? 'selected' : ''}>遍历集合</option>
                    </select>
                </div>
                <div class="mb-3 loop-count-group" ${loopType !== 'count' ? 'style="display:none;"' : ''}>
                    <label class="form-label">循环次数</label>
                    <input type="number" class="form-control step-loop-count" value="${loopCount || ''}" placeholder="循环次数">
                </div>
                <div class="mb-3 loop-expression-group" ${loopType !== 'while' ? 'style="display:none;"' : ''}>
                    <label class="form-label">循环条件</label>
                    <input type="text" class="form-control step-loop-condition" value="${loopCondition || ''}" placeholder="循环条件">
                    <div class="form-text">例如：${name}.status == 200 或 ${name}.body.success == true</div>
                </div>
                <div class="mb-3 loop-collection-group" ${loopType !== 'foreach' ? 'style="display:none;"' : ''}>
                    <label class="form-label">集合表达式</label>
                    <input type="text" class="form-control step-loop-collection" value="${loopCollection || ''}" placeholder="集合表达式">
                    <div class="form-text">例如：${name}.body.items 或 ${name}.body.data.list</div>
                </div>
                <div class="mb-3">
                    <label class="form-label">子步骤</label>
                    <div class="step-children p-2 border rounded" style="min-height: 50px;">
                        <!-- 子步骤将在这里 -->
                    </div>
                </div>
            </div>
        </div>
    `);
    
    return stepItem;
}